package com.juyu.reader.pc.service;

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.juyu.reader.pc.common.Constants;
import com.juyu.reader.pc.dao.ValidateDao;
import com.juyu.reader.pc.model.Validate;

@Service
public class ValidateService {
	Logger logger = Logger.getLogger(ValidateService.class);
	@Autowired
	public ValidateDao validateDao;

	public List<Validate> findValidate(Validate validate) {
		return validateDao.findValidate(validate);
	}

	public List<Validate> findValidateByDate(Validate validate) {
		return validateDao.findValidateByDate(validate);
	}

	public List<Validate> findValidateByIP(Validate validate) {
		return validateDao.findValidateByIP(validate);
	}

	public int insertValidate(Validate validate) {
		return validateDao.insertValidate(validate);
	}

	public int insertValidateRecord(Validate validate) {
		return validateDao.insertValidateRecord(validate);
	}

	public int deleteValidate(Validate validate) {
		return validateDao.deleteValidate(validate);
	}

	public Validate sendValidateCode(Validate validate) {
		CloseableHttpResponse response = null;
		Validate returnValidate = new Validate();
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			String str = "?name=" + Constants.VALIDATE_ACCOUNT + "&pwd=" + Constants.VALIDATE_PASSWORD + "&content="
					+ validate.getValidateContent() + "&mobile=" + validate.getValidatePhone()
					+ "&stime=&sign=【学而阅读】&type=pt&extno=";
			HttpGet httpGet = new HttpGet(Constants.VALIDATE_URL + str);
			httpGet.setHeader("Content-type", "text/html;charset:utf-8");
			response = httpclient.execute(httpGet);
			logger.info("validate status=" + response.getStatusLine());
			HttpEntity entity = response.getEntity();
			String result = EntityUtils.toString(entity, "utf-8");
			EntityUtils.consume(entity);
			logger.info("validate result=" + result);
			returnValidate.setValidateResponse(result);
			String results[] = result.split(",");
			if (results.length > 1) {
				if (results[0].equals("0")) {
					returnValidate.setSendSuccess(true);
					return returnValidate;
				} else {
					return returnValidate;
				}
			} else {
				return returnValidate;
			}
		} catch (Exception e) {
			logger.info(e.toString());
		} finally {
			try {
				response.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return returnValidate;
	}
}
